<?php
namespace Photo\Controller;
use Common\Controller\PhotoController;
class PhotoAlbumController extends PhotoController {

    public function get_config()
    {
        $input      = file_get_contents('php://input');
        $input_data = json_decode($input, true);

        if (! empty($input_data['app']) && ! empty($input_data['version']))
        {
            //跟多好玩
            $extra['app_id']    =   'wx6b1c7907c5733fc9';   //朋友小聚
            $extra['path']      =   'pages/index/index';

            $more['app_id']     =   'wx6b1c7907c5733fc9';
            $more['extra']      =   $extra;
            $more['path']       =   'pages/index/index';

            //分享
            $share['img']       =   'https://qphone.mamapai.net/album/wx/photo_share1.png';
            $share['mine']      =   '一起来传张照片拼成我们的照片墙';

            $data           =   array();
            $data['jump']   =   array();
            $data['key']    =   'EKMOWTUV3CCLErZg';
            $data['more']   =   $more;
            $data['rule']   =   array();
            $data['share']  =   $share;
            $data['version']=   100;
            $data['is_share_friend']    =   1;

            $this->returnData($data,'ok',0);
        }
    }

    //完成
    public function create_album()
    {
        $input      = file_get_contents('php://input');
        $input_data = json_decode($input, true);

        if (! empty($input_data['app']) && ! empty($input_data['version'])
        && ! empty($input_data['token']) && ! empty($input_data['template_id']))
        {
            $where['token'] =   $input_data['token'];
            $field          =   array('user_id');
            $member_data    =   M('photo_member')->where($where)->field($field)->find();
            if (! empty($member_data))
            {
                $data                       =   array();
                $where_group                =   array();
                $field_group                =   array('record_id');
                $where_group['user_id']     =   $member_data['user_id'];
                $where_group['template_id'] =   $input_data['template_id'];
                $photo_group    =   M('photo_group')->where($where_group)->field($field_group)->find();
                if (empty($photo_group))
                {
                    $insert_data                =   array();
                    $insert_data['template_id'] =   $input_data['template_id'];
                    $insert_data['user_id']     =   $member_data['user_id'];
                    $insert_data['create_time'] =   time();
                    $data['record_id']          =   M('photo_group')->add($insert_data);
                }
                else
                {
                    $data['record_id']          =   $photo_group['record_id'];
                }
                $this->returnData($data,'ok',0);
            }
            else
            {
                $data   =   array();
                $this->returnData($data,'参数错误',101);
            }
        }
        else
        {
            $data   =   array();
            $this->returnData($data,'参数错误',101);
        }
    }

    //完成
    public function get_album_photo()
    {
        $input      = file_get_contents('php://input');
        $input_data = json_decode($input, true);

        if (! empty($input_data['app']) && ! empty($input_data['version'])
            && ! empty($input_data['token']) && ! empty($input_data['record_id']))
        {
            $where['token'] =   $input_data['token'];
            $field          =   array('user_id');
            $member_data    =   M('photo_member')->where($where)->field($field)->find();
            if(empty($member_data))
            {
                $this->returnData('','参数错误',101);
            }

            $where_group                =   array();
            $field_group                =   array('record_id','template_id','user_id');
            $where_group['record_id']   =   $input_data['record_id'];
            $photo_group                =   M('photo_group')->where($where_group)->field($field_group)->find();
            if (empty($photo_group))
            {
                $this->returnData('','参数错误',1001);
            }

            //初始化
            $is_have_upload             =   0;
            $is_own                     =   0;
            $have_upload                =   array();
            $photo_list                 =   array();

            if ($photo_group['user_id'] == $member_data['user_id'])
            {
                $is_own     =   1;
            }

            $where_have                 =   array();
            $field_have                 =   array('id','record_id','position','photo_url','user_id');
            $where_have['user_id']      =   $member_data['user_id'];
            $where_have['record_id']    =   $photo_group['record_id'];
            $have_upload_data           =   M('photo_list')->where($where_have)->field($field_have)->order(array('create_time'=>'desc'))->find();

            if (! empty($have_upload_data))
            {
                $is_have_upload     =   1;
                $have_upload        =   $have_upload_data;
            }

            $where_photo_list               =   array();
            $field_list                     =   array('id','record_id','position','photo_url','user_id','nickname','avatar','create_time','update_time');
            $where_photo_list['record_id']  =   $photo_group['record_id'];
            $photo_list_data                =   M('photo_list')->where($where_photo_list)->field($field_list)->order(array('position'=>'asc'))->select();

            if (! empty($photo_list_data))
            {
                foreach ($photo_list_data as $val)
                {
                    $item               =   array();
                    $item['id']         =   $val['id'];
                    $item['photo_url']  =   $val['photo_url'];
                    $item['position']   =   $val['position'];
                    $item['record_id']  =   $val['record_id'];
                    $item['user']['avatar']     =   $val['avatar'];
                    $item['user']['id']         =   $val['user_id'];
                    $item['user']['nickname']   =   $val['nickname'];
                    $item['user_id']['nickname']=   $val['user_id'];
                    $item['update_time']        =   $val['update_time'] ? date('Y-m-d H:i:s',$val['update_time']) : date('Y-m-d H:i:s',$val['create_time']);
                    $photo_list[]   =   $item;
                }
            }

            $data                       =   array();
            $data['have_upload']        =   $have_upload;
            $data['is_have_upload']     =   $is_have_upload;
            $data['is_own']             =   $is_own;
            $data['photo_list']         =   $photo_list;
            $data['record_id']          =   $photo_group['record_id'];
            $data['template_id']        =   $photo_group['template_id'];
            $this->returnData($data,'ok',0);
        }
        else
        {
            $data   =   array();
            $this->returnData($data,'参数错误',101);
        }
    }

    //完成
    public function add_photo()
    {
        $input      = file_get_contents('php://input');
        $input_data = json_decode($input, true);

        if (! empty($input_data['app']) && ! empty($input_data['photo_url'])
        && ! empty($input_data['position']) && ! empty($input_data['record_id'])
        && ! empty($input_data['token']) && ! empty($input_data['version']))
        {
            $where['token'] =   $input_data['token'];
            $field          =   array('user_id','nickname','avatar');
            $member_data    =   M('photo_member')->where($where)->field($field)->find();
            if (! empty($member_data))
            {
                $input_data['photo_url']    =   strtolower($input_data['photo_url']);
                $replace_str                =   strtolower('http://www.ide.com/photo/PhotoAlbum/upload_d/');
                $where_group                =   array();
                $field_group                =   array('record_id','template_id','user_id');
                $where_group['record_id']   =   $input_data['record_id'];
                $photo_group_data           =   M('photo_group')->where($where_group)->field($field_group)->find();
                if (! empty($photo_group_data))
                {
                    $insert_status          =   true;   //默认是插入相册
                    if ($photo_group_data['user_id'] != $member_data['user_id'])
                    {
                        $insert_status      =   false;
                    }

                    $lists          =   explode("/",$input_data['photo_url']);
                    $key_index      =   count($lists) -1;
                    $key            =   $lists[$key_index];

                    $field_upload   =   array('url','name');
                    $img_data       =   M('photo_upload_signature')->where(array('key'=>$key))->field($field_upload)->find();

                    if (! empty($img_data))
                    {
                        $insert_data                    =   array();
                        $insert_data['record_id']       =   $input_data['record_id'];
                        $insert_data['position']        =   $input_data['position'];
                        $insert_data['photo_url']       =   $img_data['url'];
                        $insert_data['nickname']        =   $member_data['nickname'];
                        $insert_data['avatar']          =   $member_data['avatar'];
                        $insert_data['user_id']         =   $member_data['user_id'];
                        $insert_data['is_own']          =   $insert_status ? 1 : 0;     //相片主（1）0不是相片主
                        $insert_data['file_name']       =   $img_data['name'];

                        $where_photo_list               =   array();
                        $field_photo_list               =   array('record_id','user_id','position','id');
                        $where_photo_list['record_id']  =   $input_data['record_id'];
                        $where_photo_list['position']   =   $input_data['position'];
                        $is_exit                        =   M('photo_list')->where($where_photo_list)->field($field_photo_list)->find();
                        if (! empty($is_exit))
                        {
                            if ($is_exit['user_id'] != $member_data['user_id'])
                            {
                                $this->returnData(array(),'你没有权限',101);
                            }
                            $insert_data['update_time'] =   time();
                            M('photo_list')->where($where_photo_list)->save($insert_data);
                            M('photo_upload_signature')->where(array('key'=>$key))->delete();
                        }
                        else
                        {
                            $insert_data['create_time'] =   time();
                            $insert_data['update_time'] =   time();
                            M('photo_list')->add($insert_data);
                            M('photo_upload_signature')->where(array('key'=>$key))->delete();
                        }
                        $this->returnData('','ok',0);
                    }

                }

            }
            else
            {
                $data   =   array();
                $this->returnData($data,'参数错误',101);
            }
        }
        else
        {
            $data   =   array();
            $this->returnData($data,'参数错误',101);
        }
    }

    public function delete_photo()
    {
        $input      = file_get_contents('php://input');
        $input_data = json_decode($input, true);
        if (! empty($input_data['app']) && ! empty($input_data['photo_id'])
        && ! empty($input_data['record_id']) && ! empty($input_data['token'])
        && ! empty($input_data['version']))
        {
            $where['token'] =   $input_data['token'];
            $field          =   array('user_id');
            $member_data    =   M('photo_member')->where($where)->field($field)->find();
            if (! empty($member_data))
            {
                $where_group                =   array();
                $field_group                =   array('record_id','user_id');
                $where_group['record_id']   =   $input_data['record_id'];
                $photo_group    =   M('photo_group')->where($where_group)->field($field_group)->find();
                if (! empty($photo_group))
                {
                    if ($photo_group['user_id'] == $member_data['user_id'])
                    {

                        $where_list                 =   array();

                        $field_list                 =   array('file_name');

                        $where_list['record_id']    =   $input_data['record_id'];

                        $where_list['id']           =   $input_data['photo_id'];

                        $photo_list_data            =   M('photo_list')->where($where_list)->field($field_list)->find();

                        if (! empty($photo_list_data))
                        {
                            M('photo_list')->where($where_list)->delete();

                            unlink('./'.$photo_list_data['file_name'] );

                            /*
                            //删除七牛
                            $setting   = C('UPLOAD_FILE_QINIU');

                            $file_name = $photo_list_data['file_name']; //要删除的文件名称

                            $Qiniu = new \Think\Upload\Driver\Qiniu\QiniuStorage($setting['driverConfig']);

                            $result = $Qiniu->del($file_name);

                            $error = $Qiniu->errorStr;//错误信息

                            if(is_array($result) && !($error))
                            {
                                $data['msg']   =   '删除文件成功';
                            }
                            else
                            {
                                $data['msg']   =   '删除文件失败，'.$error;
                            }
                            */

                            $this->returnData($data,'ok',0);

                        }

                    }
                }
            }
            else
            {
                $this->returnData('','参数错误',101);
            }
        }
        else
        {
            $this->returnData('','参数错误',101);
        }
    }

    public function get_qrcode()
    {
        $input      = file_get_contents('php://input');
        $input_data = json_decode($input, true);
        if (! empty($input_data['app']) && ! empty($input_data['page'])
        && ! empty($input_data['scene']) && ! empty($input_data['token'])
        && ! empty($input_data['version']))
        {
            $log['module']     =   'photo';
            $log['log']         =   '开始时间：'.time();
            M('yao_log')->add($log);


            $scene_index    =   explode("=",$input_data['scene']);
            $where_group            =   array();
            $field                  =   array('record_id','qrcode');
            $where_group['record_id']=  $scene_index[1];
            $photo_group_data   =   M('photo_group')->where($where_group)->field($field)->find();

            $log['module']     =   'photo';
            $log['log']         =   '开始时间 1：'.time();
            M('yao_log')->add($log);

            if (! empty($photo_group_data['qrcode']))
            {
                $log['module']     =   'photo';
                $log['log']         =   '结束时间1：'.time();
                M('yao_log')->add($log);

                $data   =   array();
                $data   =   $photo_group_data['qrcode'];
                $this->returnData($data,'ok',0);
            }
            else
            {
                $access_token = $this->accesstoken();
                $url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token='.$access_token;
                $path="pages/index?record_id=".$photo_group_data['record_id']."&id=".$photo_group_data['record_id'];
                $width=430;
                $data='{"path":"'.$path.'","width":'.$width.'}';
                $return = $this->request_post($url,$data);

                $qrcode_path    =   './Public/data/photo/qrcode/';
                $web_path       =   'Public/data/photo/qrcode/';

                //将生成的小程序码存入相应文件夹下
                if (! is_dir($qrcode_path))
                {
                    mkdir($qrcode_path);
                }

                $result     =   file_put_contents($qrcode_path.$photo_group_data['record_id'].'.jpg',$return);

                $log['module']     =   'photo';
                $log['log']         =   '结束时间2：'.time();
                M('yao_log')->add($log);

                if (! empty($result ))
                {
                    $update_data            =   array();
                    $update_data['qrcode']  =   'https://api.beikg.cn/'.$web_path.$photo_group_data['record_id'].'.jpg';
                    M('photo_group')->where($where_group)->save($update_data);

                    $data   =   array();
                    $data   =   $update_data['qrcode'];
                    $this->returnData($data,'ok',0);
                }

            }
        }
    }

    //完成
    public function upload_signature()
    {
        $input      = file_get_contents('php://input');
        $input_data = json_decode($input, true);

        if (! empty($input_data['app']) && ! empty($input_data['version']) && ! empty($input_data['token']))
        {
            $where['token'] =   $input_data['token'];
            $field          =   array('user_id');
            $member_data    =   M('photo_member')->where($where)->field($field)->find();
            if (! empty($member_data))
            {
                //删除过期数据
                $where_del          =   array();
                $where_del['expire']=   array('LT',time());
                M('photo_upload_signature')->where($where_del)->delete();

                $data               =   array();
                $data['access_id']  =   $member_data['user_id'];
                $data['expire']     =   time() + 60*30;
                $data['host']       =   'https://api.beikg.cn/photo/PhotoAlbum/upload_do';  //https://api.beikg.cn/photo/PhotoAlbum/upload_do
                $data['key']        =   date('YmdHis').'_'.$member_data['user_id'];
                $data['policy']     =   md5($data['access_id']);
                $data['signature']  =   md5($data['access_id'].$data['expire']);
                M('photo_upload_signature')->add($data);
                $this->returnData($data,'ok',0);
            }
            else
            {
                $data   =   array();
                $this->returnData($data,'参数错误',101);
            }
        }

        $data   =   array();
        $this->returnData($data,'参数错误',101);
    }

    //完成
    public function upload_do()
    {
        if (IS_POST && ! empty($_POST) && ! empty($_FILES))
        {
            if (! empty($_POST['key']) && ! empty($_POST['name']))
            {
                $upload = new \Think\Upload();// 实例化上传类
                $upload->maxSize   =     3145728 ;// 设置附件上传大小
                $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
                $upload->rootPath  =     './Public/data/photo/'; // 设置附件上传根目录
                $savePath           =    'Public/data/photo/'; // 设置附件上传（子）目录
                // 上传文件
                $info   =   $upload->upload();

                /*
                 //七牛
                $setting                =   C('UPLOAD_SITEIMG_QINIU');
                $setting['saveName']    =   $_POST['key'];
                $setting['savePath']    =   'photo/upload/';
                $Upload                 =   new \Think\Upload($setting);
                $info                   =   $Upload->upload($_FILES);
                */

                if (! empty($info))
                {
                    //https://api.beikg.cn/photo/PhotoAlbum/upload_do
                    $host                   =   'https://api.beikg.cn/';
                    $update_data            =   array();
                    $update_data['savename']=   $info['file']['savename'];
                    $update_data['url']     =   $host.$savePath.$info['file']['savepath'].$info['file']['savename'];
                    $update_data['name']    =   $savePath.$info['file']['savepath'].$info['file']['savename'];
                    $update_data['ext']     =   $info['file']['ext'];
                    M('photo_upload_signature')->where(array('key'=>$_POST['key']))->save($update_data);
                }
            }
        }

    }

    //(完成)
    public function get_user_group()
    {
        $input      = file_get_contents('php://input');
        $input_data = json_decode($input, true);

        if (! empty($input_data['app']) && ! empty($input_data['version']) && ! empty($input_data['token']))
        {
            $data   =   array();
            $where['token'] =   $input_data['token'];
            $field          =   array('yao_member_id');
            $member_data    =   M('yao_member')->where($where)->field($field)->find();
            if (! empty($member_data ))
            {
                $where_group_member             =   array();
                $field_group_member             =   array('id','group_id');
                $where_group_member['user_id']  =   $member_data['yao_member_id'];
                $group_member   =   M('yao_group_member')->where($where_group_member)->field($field_group_member)->select();
                if (! empty($group_member))
                {
                    $where_group        =   array();
                    $list_group_id      =   array();
                    $field_group        =   array('id','group_name','group_id','create_time','update_time');
                    foreach ($group_member as $val)
                    {
                        $list_group_id[]    =   $val['group_id'];
                    }
                    $where_group['group_id']  = array('between',$list_group_id);

                    $group_member   =   M('yao_group')->where($where_group)->field($field_group)->select();

                    if (! empty($group_member))
                    {
                        foreach ($group_member as $vals)
                        {
                            $group_val      =   array();
                            $group_val['group_id']  =   $vals['group_id'];
                            $group_val['group_name']['create_time'] =   $vals['create_time'];
                            $group_val['group_name']['group_id']    =   $vals['group_id'];
                            $group_val['group_name']['id']          =   $vals['id'];
                            $group_val['group_name']['name']        =   $vals['group_name'];
                            $group_val['group_name']['update_time'] =   $vals['update_time'];
                            $data[]         =  $group_val;
                        }
                    }

                }

                $this->returnData($data,'ok',0);
            }
            else
            {
                $this->returnData('','please login',101);
            }
        }

        $data   =   array();
        $this->returnData($data,'参数错误',1001);
    }

    //(完成)
    public function share()
    {
        $input      = file_get_contents('php://input');
        $input_data = json_decode($input, true);
        if (! empty($input_data) || $_POST)
        {
            if (! empty($input_data['app']) && ! empty($input_data['version'])
                && ! empty($input_data['token']) && ! empty($input_data['iv'])
                && ! empty($input_data['encryptedData']) && ! empty($input_data['code']))
            {
                $where['token'] =   $input_data['token'];
                $field          =   array('yao_member_id','session_key','openid','nickname','avatar');
                $member_data    =   M('yao_member')->where($where)->field($field)->find();

                if (! empty($member_data))
                {
                    $appid      = 'wxec5cdb888a5fcdda';
                    $sessionkey = $member_data['session_key'];
                    //解析openGId
                    $openGId = $this->getopenGId($appid,$sessionkey,$input_data['encryptedData'],$input_data['iv']);

                    if ($openGId != -1)
                    {
                        //创建群
                        $where_group['group_id']    =   $openGId;
                        $field                      =   array('group_id');
                        $group_data     =   M('yao_group')->where($where_group)->field($field)->find();

                        if (empty($group_data))
                        {
                            $insert_group   =   array();
                            $insert_group['group_id']       =   $openGId;
                            $insert_group['create_time']    =   time();
                            $insert_group['update_time']    =   time();
                            M('yao_group')->add($insert_group);
                        }

                        //加入群
                        $where_group_member    =   array();
                        $where_group_member['user_id']  =   $member_data['yao_member_id'];
                        $where_group_member['group_id'] =   $openGId;
                        $is_exit    =   M('yao_group_member')->where($where_group_member)->field($field)->find();
                        if (empty($is_exit))
                        {
                            $join_group                 =   array();
                            $join_group['user_id']      =   $member_data['yao_member_id'];
                            $join_group['nickname']     =   $member_data['nickname'];
                            $join_group['avatar']       =   $member_data['avatar'];
                            $join_group['group_id']     =   $openGId;
                            $join_group['create_time']  =   time();
                            M('yao_group_member')->add($join_group);
                        }

                        $data['group_id']   =   $openGId;
                        $this->returnData($data,$msg='ok',$code=0);
                    }
                    else
                    {
                        $this->returnData('','获取群id错误',101);
                    }
                }
                else
                {
                    $this->returnData('','please login',101);
                }
            }
        }

        $data   =   array();
        $this->returnData($data,'参数错误',1001);

    }

    public function accesstoken()
    {
        $AccessToken =  S('Photo_AccessToken');//设置缓存标示
        if (! empty($AccessToken))
        {
            $AccessToken    =   json_decode($AccessToken , true);
            if (! empty($AccessToken['access_token']))
            {
                return $AccessToken['access_token'];
            }
        }

        $APPID       = 'wxec5cdb888a5fcdda';
        $APPSECRET   = 'c7e47535ef8a22a6e2b0a5730a8f57ba';
        $url         = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$APPID.'&secret='.$APPSECRET;
        $AccessToken = $this->request_post($url, array()); //file_get_contents($url);
        S('Photo_AccessToken',$AccessToken,7200);
        $AccessToken = json_decode($AccessToken , true);
        $AccessToken = $AccessToken['access_token'];
        return $AccessToken;
    }

    public function request_post($url, $data)
    {
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        }else{
            return $tmpInfo;
        }
    }
}